# This is a sample Python script.
import json
import subprocess
import time
import traceback
from datetime import datetime

from bs4 import BeautifulSoup
from selenium.webdriver import DesiredCapabilities
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.support.wait import WebDriverWait

from apscheduler.executors.pool import ThreadPoolExecutor
from apscheduler.schedulers.background import BackgroundScheduler
from apscheduler.schedulers.blocking import BlockingScheduler
from apscheduler.triggers.cron import CronTrigger
from apscheduler.triggers.interval import IntervalTrigger

import requests

import util
from Element import Element

browser_map_list = []

el = Element()


def send_data(data):
    # dumpsJson = json.dumps(data, ensure_ascii=False);
    print(data)
    if True:
        return
    # 发送 POST 请求
    url = 'http://localhost:3000/nftapi/v1/element'
    headers = {'Content-Type': 'application/json'}
    response = requests.post(url, json=data, headers=headers)

    # 检查响应状态码
    if response.status_code == 200:
        # 处理响应数据
        data = response.json()  # 假设响应是 JSON 格式
        print(data)
    else:
        print('请求失败:', response.status_code)


def get_element_data():
    driver = util.get_chrome_html_driver()
    configPath = "F:\\workspace_coin\\future_sys\\node_programs\\buss\marketplace\config\\intswap_collection_config.json"
    # configPath = "intswap_collection_config.json"
    with open(configPath, "r", encoding="utf-8") as f:
        collectionArr = json.load(f)
        for collection in collectionArr:
            print('name:', collection["name"], '合约地址：', collection["contractAddress"])
            body = el.get_items(driver, collection["contractAddress"])
            if body is not None:
                body['name'] = collection["name"]
                send_data(body)
                try:
                    detail = el.get_detail(collection['detailUrl'], driver)
                    send_data({"type": "buy_detail", "name": collection['name'], "data": detail})
                except Exception as e:
                    print(e)
    driver.quit()


if __name__ == '__main__':
    # subprocess.Popen(['C:\Program Files\Google\Chrome\Application\chrome.exe', '--remote-debugging-port=9222'])
    scheduler = BlockingScheduler()
    # 循环任务，每30秒执行一次  (由于你本地代码不立刻启动而是30秒后才执行第一次，我还是用了库 pip install apscheduler)
    scheduler.add_job(get_element_data, IntervalTrigger(seconds=30, start_date=datetime.now()))
    print("start")
    scheduler.start()
    # for i in range(0,3):
    #     port = 9222 + i
    #     subprocess.Popen(['C:\Program Files\Google\Chrome\Application\chrome.exe', '--remote-debugging-port={0}'.format(port),'--user-data-dir=C:/selenum/AutomationProfile'+str(i)])
    #     # subprocess.Popen(['C:\Program Files\Google\Chrome\Application\chrome.exe', '--remote-debugging-port={0}'.format(port)])
    #     browser_map_list.append({'port':port,'pid':None,'status':'idle'})
    # executor = ThreadPoolExecutor(max_workers=5)
    # scheduler = BlockingScheduler(executors={'default': executor})
    # scheduler.add_job(get_data, IntervalTrigger(seconds=15),max_instances=3)
    # scheduler.add_job(get_data, IntervalTrigger(seconds=25),max_instances=3)
    # scheduler.add_job(get_data, IntervalTrigger(seconds=20),max_instances=3)
    # scheduler.start()
    # get_detail()
    # get_data()
    # p.terminate()
